import { login, getInfo } from "@/http/api/index";
import { tokenGet, tokenSet, deleteToken } from "@/utils/tokenManage";

const user = {
  state: {
    /*可以用做没有权限的操作员*/
    roleTemplate: {
      origin: {
        add: false,
        update: false,
        delete: false,
        select: true,
        isShow: true,
      },
      device: {
        add: false,
        select: true,
        update: false,
        delete: false,
        oper: false,
        isShow: true,
      },
      user: {
        add: false,
        select: true,
        update: false,
        delete: false,
        upload: false,
        isShow: true,
      },
      role: {
        add: false,
        select: true,
        update: false,
        delete: false,
        isShow: true,
      },
      opendoorlog: {
        select: true,
        isShow: true,
      },
      alarmlog: {
        select: true,
        isShow: true,
      },
      operlog: {
        select: true,
        isShow: true,
      },
      config: {
        select: false,
        oper: false,
        isShow: true,
      },
    },
    roleTableList: [
      { key: "origin", name: "区域管理" },
      { key: "device", name: "设备管理" },
      { key: "user", name: "用户管理" },
      { key: "role", name: "角色管理" },
      { key: "opendoorlog", name: "开门日志" },
      { key: "alarmlog", name: "报警日志" },
      { key: "operlog", name: "操作日志" },
      { key: "config", name: "系统配置" },
    ],
    // 登录者信息 - 用户信息userInfo  
    userInfo: {},
    // 权限
    roles: {},
    // 基础数据 - configs
    baseInfo: {},
  },

  mutations: {
    SET_INFO: (state, info) => {
      //用户信息赋值
      if (info.userInfo && info.userInfo.userimg) {
        info.userInfo.userimg = window.location.origin + info.userInfo.userimg;
      }
      state.userInfo = info.userInfo || {};
      if (info.configs && info.configs.icon) {
        info.configs.icon = window.location.origin + info.configs.icon;
      }
      state.baseInfo = info.configs || {};
      state.roles = info.roles || {};
    },
    SET_USERINFO: (state, info) => {
      if (info.userInfo && info.userInfo.userimg && !info.userInfo.userimg.includes("hhtp")) {
        info.userInfo.userimg = window.location.origin + info.userInfo.userimg;
      }
      state.userInfo = info;
    },
    SET_CONFIG: (state, config) => {
      if (config && config.icon && !config.icon.includes("http")) {
        config.icon = window.location.origin + config.icon;
      }
      state.baseInfo = config || {};
    },
  },

  actions: {
    // 登录
    Login({ dispatch }, userInfo) {
      return new Promise((resolve, reject) => {
        // console.log(userInfo, "--login")
        login(userInfo)
          .then((response) => {
            if (response.code != 200) {
              resolve({ code: 500 });
              return;
            }
            const tokenStr = response.token;
            tokenSet(tokenStr, response.usetime);
            localStorage.setItem("username", userInfo.username);
            localStorage.setItem("password", userInfo.password);
            console.log("进入");
            dispatch("GetInfo", userInfo.username);
            resolve({ code: 200 });
          })
          .catch((error) => {
            resolve({ code: 500, remark: '服务异常' });
          });
        return;
      });
    },
    // 检测是否已经登录
    checkLogin({ dispatch }, userInfo) {
      return new Promise((resolve, reject) => {
        if (tokenGet()) {
          dispatch("GetInfo", userInfo.username)
            .then((res) => {
              if (res.code == 200) {
                resolve({ code: 200 });
              } else {
                // console.log("检测未登录 --删除 token")
                // deleteToken();
                resolve({ code: 500, remark: res.remark });
              }
            })
            .catch((err) => {
              resolve({ code: 500 });
            });

          return;
        } else {
          resolve({ code: 500 });
        }
      });
    },
    makeRoleOper({ }, { type, obj }) {
      if (type == 1) {
        for (const key in obj) {
          if (typeof obj[key] === "object") {
            for (let v in obj[key]) {
              obj[key][v] = true;
            }
          } else if (typeof obj[key] === "boolean") {
            obj[key] = true;
          }
        }
      } else if (type == 2) {

      } else if (type == 'admin') {
        obj = {
          origin: {
            add: false,
            update: false,
            delete: false,
            select: false,
            isShow: false,
          },
          device: {
            add: false,
            select: false,
            update: false,
            delete: false,
            oper: false,
            isShow: false,
          },
          user: {
            add: true,
            select: true,
            update: true,
            delete: true,
            upload: true,
            isShow: true,
          },
          role: {
            add: false,
            select: true,
            update: false,
            delete: false,
            isShow: false,
          },
          opendoorlog: {
            select: false,
            isShow: false,
          },
          alarmlog: {
            select: false,
            isShow: false,
          },
          operlog: {
            select: false,
            isShow: false,
          },
          config: {
            select: true,
            oper: true,
            isShow: true,
          },
        }
      }
      return obj;
    },
    // 获取用户信息
    GetInfo({ dispatch, commit, state }, username) {
      return new Promise((resolve, reject) => {
        getInfo({ username })
          .then(async (response) => {
            let userInfo = {};
            // info = {code, userInfo, roles, configs}
            const info = response;
            if (info.code != 200) {
              resolve({ code: 500, remark: info.remark });
              return;
            }
            let code = localStorage.getItem("username");
            if (code != info.userInfo.code) {
              console.log("当前账号与登录账号不一致 -- 删除token")
              deleteToken();
              resolve({ code: 500, remark: "当前账号与登录账号不一致!" });
              return;
            }

            // 用户信息
            userInfo.userInfo = info.userInfo;
            // 判断权限
            let roles = {};
            if (info.userInfo.code == "admin") {
              // 只能操作 用户和配置
              roles = await dispatch("makeRoleOper", { type: 'admin', obj: {} });
            } else if (info.roles != "{}") {
              roles = JSON.parse(info.roles);
            } else {
              if (info.userInfo.identityid == 1) {
                // 管理员 - 默认全部权限
                console.log(state.roleTemplate, "state.roleTemplate")
                roles = await dispatch('makeRoleOper',
                  {
                    type: 1,
                    obj: JSON.parse(JSON.stringify(state.roleTemplate))
                  }
                );
              } else {
                // 操作员 - 默认查看的权限
                roles = await dispatch('makeRoleOper',
                  {
                    type: 2,
                    obj: JSON.parse(JSON.stringify(state.roleTemplate))
                  }
                )
              }

            }
            console.log(roles, "---")
            userInfo.roles = roles;
            let configs = {};
            for (let item in info.configs) {
              configs[item] = info.configs[item].configV;
            }
            configs.login_disabled = info.configs.login_disabled == "1" ? true : false;
            configs.auto_clean_log = info.configs.auto_clean_log == "1" ? true : false;
            configs.pwd_complex = configs.pwd_complex.split("")
            userInfo.configs = configs;
            commit('CHANGE_MENU', userInfo.roles);
            commit("SET_INFO", userInfo);
            resolve({ code: 200 });
          })
          .catch((error) => {
            console.log(error, "--error");
            resolve({ code: 500, remark: "获取信息失败" });
          });
      });
    },

    // 登出
    LogOut({ commit, state }, param) {
      return new Promise((resolve, reject) => {
        console.log("登出的删除 - token");
        deleteToken();
        commit("SET_INFO", {});
        resolve(200);
      });
    },
  },
};

export default user;
